package com.qqhf.hitfood.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qqhf.common.entity.AjaxResult;
import com.qqhf.common.entity.Constants;
import com.qqhf.common.entity.PageEntity;
import com.qqhf.common.utils.RandomUtils;
import com.qqhf.hitfood.bean.core.BaseController;
import com.qqhf.hitfood.bean.dto.BizOrderDto;
import com.qqhf.hitfood.bean.dto.BizOrderFoodDto;
import com.qqhf.hitfood.bean.entity.BizFood;
import com.qqhf.hitfood.bean.entity.BizOrder;
import com.qqhf.hitfood.bean.entity.BizOrderFood;
import com.qqhf.hitfood.bean.entity.BizShop;
import com.qqhf.hitfood.bean.vo.CartItemVo;
import com.qqhf.hitfood.service.*;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.nutz.json.Json;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api(tags = "B - 订单")
@RestController
@RequestMapping("/biz/order")
public class BizOrderController extends BaseController {
    @Autowired
    private IBizOrderService bizOrderService;
    @Autowired
    private IBizOrderFoodService bizOrderFoodService;
    @Autowired
    private IPosAddressService posAddressService;
    @Autowired
    private IBizShopService bizShopService;
    @Autowired
    private IBizFoodService bizFoodService;
    @Autowired
    private IAcctUserService acctUserService;

    @Operation(summary = "下订单：用户、店铺、地址、购物车")
    @PostMapping("/place")
    public AjaxResult place(HttpServletRequest request) {
        Map data = getRequestPayload(Map.class);
        System.out.println(Json.toJson(data));
        Integer addressId = Integer.valueOf(data.get("address_id").toString());
        Integer shopId = Integer.valueOf(data.get("shop_id").toString());
        Integer userId = Integer.valueOf(data.get("user_id").toString());
        Double feeTotal = Double.valueOf(data.get("total").toString());
        List<CartItemVo> foods = JSON.parseArray(JSON.toJSON(data.get("cart")).toString(), CartItemVo.class);

        String orderNum = RandomUtils.getUUIDRandom();
        BizOrder bizOrder = new BizOrder();
        bizOrder.setOrderNum(orderNum);
        bizOrder.setUserId(userId);
        bizOrder.setShopId(shopId);
        bizOrder.setAddressId(addressId);
        bizOrder.setFeeTotal(feeTotal);
        System.out.println("bizOrder:" + bizOrder);
        boolean saveOrder = bizOrderService.save(bizOrder);
        if (saveOrder) {
            boolean savefoods = true;
            for (CartItemVo food : foods) {
                BizOrderFood bizOrderFood = new BizOrderFood();
                bizOrderFood.setOrderNum(orderNum);
                bizOrderFood.setShopId(shopId);
                bizOrderFood.setFoodId(food.getId());
                bizOrderFood.setQuantity(food.getNum());
                System.out.println("bizOrderFood" + food.getId() + ":" + bizOrderFood);
                boolean save = bizOrderFoodService.save(bizOrderFood);
                savefoods = savefoods && save;
            }
            if (savefoods) {
                return AjaxResult.success("下单成功", orderNum);
            }
        }
        return AjaxResult.error("下单失败");
    }

    @Operation(summary = "改变订单状态")
    @PutMapping("/changeSt")
    public AjaxResult changeSt(
            @RequestParam(value = "orderNum") String orderNum,
            @RequestParam(value = "stId") Integer stId) {
        System.out.println("orderNum:" + orderNum);
        System.out.println("stId:" + stId);
        boolean success = true;
        BizOrder bizOrder = bizOrderService.getOne(new QueryWrapper<BizOrder>().eq("order_num", orderNum), false);
        bizOrder.setStId(stId);
        boolean b = bizOrderService.updateById(bizOrder);
        if (b) {
            if (stId == Constants.ST_ORDER_PAIED) {
                BizShop bizShop = bizShopService.getById(bizOrder.getShopId());
                bizShop.setSalesMth(bizShop.getSalesMth() + 1);
                bizShop.setSalesTtl(bizShop.getSalesTtl() + 1);
                bizShopService.updateById(bizShop);
            }
            List<BizOrderFood> foods = bizOrderFoodService.list(new QueryWrapper<BizOrderFood>().eq("order_num", orderNum));
            for (BizOrderFood food : foods) {
                food.setStId(stId);
                bizOrderFoodService.updateById(food);
            }
            List<BizOrderFood> bizOrderFoods = bizOrderFoodService.list(new QueryWrapper<BizOrderFood>().eq("order_num", orderNum));
            for (BizOrderFood bizOrderFood : bizOrderFoods) {
                bizOrderFood.setStId(stId);
                if (stId == Constants.ST_ORDER_PAIED) {
                    BizFood bizFood = bizFoodService.getById(bizOrderFood.getFoodId());
                    bizFood.setSalesMth(bizFood.getSalesMth() + 1);
                    bizFood.setSalesTtl(bizFood.getSalesTtl() + 1);
                    bizFoodService.updateById(bizFood);
                }
                success = success && bizOrderFoodService.updateById(bizOrderFood);
            }
            if (success)
                return AjaxResult.success("状态更新成功");
        }
        return AjaxResult.error("状态更新失败");
    }

    @Operation(summary = "获取用户的订单列表")
    @GetMapping("/listByUserId")
    public AjaxResult listByUserId(@RequestParam(value = "userId") String userId) {
        return AjaxResult.success(toDto(bizOrderService.list(new QueryWrapper<BizOrder>().eq("user_id", userId).orderByDesc("create_time"))));
    }

    @Operation(summary = "搜索订单列表:订单号、店铺id、用户id、订单状态")
    @GetMapping("/search")
    public AjaxResult search(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "shopId", required = false) Integer shopId,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "stId", required = false) Integer stId) {
        QueryWrapper<BizOrder> wrapper = new QueryWrapper<BizOrder>();
        if (keyword != null && keyword.length() > 0)
            wrapper.like("order_num", keyword);
        if (shopId != null)
            wrapper.eq("shop_id", shopId);
        if (userId != null)
            wrapper.eq("user_id", userId);
        if (stId != null)
            wrapper.eq("st_id", stId);
        return AjaxResult.success(toDto(bizOrderService.list(wrapper.orderByDesc("create_time"))));
    }

    @Operation(summary = "分页获取订单列表")
    @GetMapping("/page")
    public AjaxResult page(PageEntity pageEntity, BizOrder bizOrder) {
        return AjaxResult.success(bizOrderService.page(pageEntity.toPage(), Wrappers.lambdaQuery(bizOrder)));
    }

    @Operation(summary = "获取所有订单列表")
    @GetMapping("/list")
    public AjaxResult list() {
        return AjaxResult.success(toDto(bizOrderService.list(new QueryWrapper<BizOrder>().orderByDesc("create_time"))));
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody BizOrder bizOrder) {
        return AjaxResult.success(bizOrderService.save(bizOrder));
    }

    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody BizOrder bizOrder) {
        return AjaxResult.success(bizOrderService.updateById(bizOrder));
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Integer id) {
        BizOrder order = bizOrderService.getById(id);
        if (order != null) {
            String orderNum = order.getOrderNum();
            boolean b = bizOrderService.removeById(id);
            boolean s = true;
            if (b) {
                List<BizOrderFood> foods = bizOrderFoodService.list(new QueryWrapper<BizOrderFood>().eq("order_num", orderNum));
                for (BizOrderFood food : foods) {
                    s = s && bizOrderFoodService.removeById(food);
                }
                if (s)
                    return AjaxResult.success("删除成功");
            }
        }
        return AjaxResult.error("删除失败");
    }

    @GetMapping(value = "/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Integer id) {
        return AjaxResult.success(bizOrderService.getById(id));
    }

    /**
     * 包装后类型从id变为实体
     *
     * @param list
     * @return
     */
    public List<BizOrderDto> toDto(List<BizOrder> list) {
        List<BizOrderDto> bizOrderDtos = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            BizOrder bizOrder = list.get(i);
            BizOrderDto bizOrderDto = new BizOrderDto();
            BeanUtils.copyProperties(bizOrder, bizOrderDto);
            bizOrderDto.setAddress(posAddressService.getById(bizOrder.getAddressId()));
            bizOrderDto.setShop(bizShopService.getById(bizOrder.getShopId()));
            bizOrderDto.setFoods(bizOrderFoodtoDto(bizOrderFoodService.list(new QueryWrapper<BizOrderFood>().eq("order_num", bizOrder.getOrderNum()))));
            bizOrderDto.setUserName(acctUserService.getById(bizOrderDto.getUserId()).getName());
            bizOrderDtos.add(bizOrderDto);
        }
        return bizOrderDtos;
    }

    public List<BizOrderFoodDto> bizOrderFoodtoDto(List<BizOrderFood> list) {
        List<BizOrderFoodDto> bizOrderDtos = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            BizOrderFood bizOrderFood = list.get(i);
            BizOrderFoodDto bizOrderFoodDto = new BizOrderFoodDto();
            BeanUtils.copyProperties(bizOrderFood, bizOrderFoodDto);
            bizOrderFoodDto.setFood(bizFoodService.getById(bizOrderFood.getFoodId()));
            bizOrderDtos.add(bizOrderFoodDto);
        }
        return bizOrderDtos;
    }
}
